package top.codingfly.netty.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.json.JsonObjectDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public abstract class NettyHandler {

    private final static Logger logger = LoggerFactory.getLogger(NettyHandler.class);

    // 解决粘包拆包和转成对象在同一个decode方法
    public abstract void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception;

    // 发送数据
    public abstract <T> void encode(ChannelHandlerContext ctx, T msg, ByteBuf out) throws Exception;

    /****** 接收数据转成对象后, 只有这里一个入口处理接收的对象 ******/
    public abstract <T> void handle(ChannelHandlerContext ctx, T msg) throws Exception;

    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelRegistered {}", ctx.channel().remoteAddress());
    }

    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelUnregistered {}", ctx.channel().remoteAddress());
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelActive {}", ctx.channel().config());
    }

    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("channelInactive {}", ctx.channel().config());
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage(), cause);
        logger.info("exceptionCaught {}", ctx.channel().config());
    }

}
